/*
 * Created on May 3, 2004
 *
 * Vectrics Inc.  GNU Public License.
 */
package org.vectrics.recruiter.reporting;

import java.awt.Color;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPCell;
import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.VectricsException;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.config.RecruitConfig;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobSearchCriteria;
import org.vectrics.recruiter.job.JobProvider;
import org.vectrics.recruiter.job.JobStatusType;
import org.vectrics.struts.PhraseManager;
import org.vectrics.common.reporting.pdf.ReportUtil;
import org.vectrics.company.Company;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;

import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import java.text.*;


/**
 * @author mmoore
 */
public class JobListPdfTable extends PdfPTable {
	private transient static Logger log = Logger.getLogger(JobListPdfTable.class);
	private boolean activeOnly = false;
	private Company company = null;
	private Color ACTIVE_COLOR = new Color(255, 248, 210);
	private SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy");
	private static int numberOfColumns = 6;
	private Locale locale = null;
	private Domain domain = null;
	
	public JobListPdfTable(Domain domain, Locale locale) {
		super(numberOfColumns);
		this.locale = locale;
		this.domain = domain;
	}
	
	protected String getPhrase(String code) {
		String name = CoreServiceLocator.getPhraseProvider().getMessage(code, this.locale);
		return(name);
	}
	
	private String getPathCompanyName(Company company) {
		String name = "";
		Company parent = company.getParent();
		if (parent == null) {
			name = company.getName();
		}
		else {
			name = parent.getName() + " - " + company.getName();
		}
		return(name);
	}
	

	public void fill() throws VectricsException {
		int headerRowCount = 1;
		
		log.debug("fill() - setting table properties");
		this.setHorizontalAlignment(Element.ALIGN_LEFT);
		this.setWidthPercentage(100);
		int thisWidths[] = {60, 53, 105, 80, 100, 100};
		if (thisWidths.length != numberOfColumns)
			throw new SystemException("Column width settings not same number as column count");
		try {
			this.setWidths(thisWidths);
		} catch (Exception ex) {
			throw new VectricsException("Exception setting widths", ex);
		}
		
		if (company != null) {
			headerRowCount++;
			String companyName = getPathCompanyName(company);
			PdfPCell hdrCell = new PdfPCell(new Phrase(companyName, ReportConstants.titleFont));
			hdrCell.setColspan(numberOfColumns);
			this.addCell(hdrCell);
		}
		
		log.debug("fill() - adding table header row");
		addTableHeaderCell(this.getPhrase("prompt.job.date.posted"));
		addTableHeaderCell(this.getPhrase("prompt.job.reference.id"));
	
		if (RecruitConfig.getRecruitInstance().getAllowMultipleCompanies(domain)) {
			addTableHeaderCell(this.getPhrase("phrase.company"));
		}	
		addTableHeaderCell(this.getPhrase("prompt.job.title"));
		addTableHeaderCell(this.getPhrase("prompt.job.location"));
		addTableHeaderCell(this.getPhrase("phrase.job.summary"));
		this.setHeaderRows(headerRowCount);
	
		log.debug("fill() - adding job rows");
		Collection jobs = null;
		JobSearchCriteria criteria = new JobSearchCriteria();
		if (this.activeOnly) {
			criteria.addStatusTypeCode(JobStatusType.STATUS_POSTED);
		}
		
		Set domains =  CoreServiceLocator.getPersonService().findDomainsThatPersonCanAccess(ThreadProperties.getPerson());
		criteria.setDomains(domains);
		if (company != null) {
			criteria.addCompany(company);
		} else {
			log.debug("Jobs for all companies will be found");
		}
		jobs = RecruitServiceLocator.getJobProvider().findJobs(criteria, 0, 5000);
		
		if (jobs.size() > 0) {
			Iterator iter = jobs.iterator();
			while (iter.hasNext()) {
				Job job = (Job)iter.next();
				if (job == null) {
					log.error("fill() - could not find jobId = " + job.getId());	
				}
				else {
					addJobRow(job);
				}
			}
		} else {
			PdfPCell hdrCell = new PdfPCell(new Phrase(this.getPhrase("phrase.jobs.none.found"), 
					ReportConstants.stdItalicsFont));
			hdrCell.setColspan(numberOfColumns);
			addCell(hdrCell);
		}
		log.debug("fill() - adding job table to document");
	}
	

	protected void addTableHeaderCell(String title) {
		log.debug("addTableHeaderCell()");
		PdfPCell hdrCell = new PdfPCell(new Phrase(title, ReportConstants.stdBoldFont));
		hdrCell.setBackgroundColor(ReportConstants.TABLE_HEAD_COLOR);
		this.addCell(hdrCell);	
	}
	

	protected void addJobRow(Job job) throws VectricsException {
		try {
			Color color = new Color(255, 255, 255);
			
			log.debug("addJobRow() - called");
			if ((getActiveOnly() == false) && (job.getCurrentStatus().getStatusType().getCode().equals(JobStatusType.STATUS_POSTED))) 
				color = ACTIVE_COLOR;
			
			log.debug("addJobRow() - displaying date...");
			String dateStr = "Not Given";
			if (job.getDatePosted() != null) {
				dateStr = dateFormatter.format(job.getDatePosted());	
			}
			PdfPCell cell = new PdfPCell(ReportUtil.createPhrase(dateStr, ReportConstants.stdFont));
			cell.setBackgroundColor(color);
			this.addCell(cell);	
			
			log.debug("addJobRow() - displaying reference id...");
			cell = new PdfPCell(ReportUtil.createPhrase(job.getReferenceId(), ReportConstants.stdFont));
			cell.setBackgroundColor(color);
			this.addCell(cell);	

			if (RecruitConfig.getRecruitInstance().getAllowMultipleCompanies(domain)) {
				log.debug("addJobRow() - displaying company");
				cell = new PdfPCell(ReportUtil.createPhrase(getCompanyName(job), ReportConstants.stdFont));
				cell.setBackgroundColor(color);
				this.addCell(cell);
			}	
			
			log.debug("addJobRow() - displaying job title...");
			cell = new PdfPCell(ReportUtil.createPhrase(job.getTitle(), ReportConstants.stdFont));
			cell.setBackgroundColor(color);
			this.addCell(cell);	
			
			log.debug("addJobRow() - displaying job location...");
			cell = new PdfPCell(ReportUtil.createPhrase(job.getLocationDescription(), ReportConstants.stdFont));
			cell.setBackgroundColor(color);
			this.addCell(cell);	
			
			
			log.debug("addJobRow() - displaying summary...");
			String summaryStr = "";
			if (this.getActiveOnly() == false) {
				summaryStr += job.getCurrentStatus().getStatusType().getDescription(locale) + " / ";
				
			}
			if (job.getFeatured()) {
				summaryStr += "Featured / ";
			}
			if (summaryStr.endsWith(" / ")){
				summaryStr = summaryStr.substring(0, summaryStr.length() - 3);
			}
			cell = new PdfPCell(ReportUtil.createPhrase(summaryStr, ReportConstants.stdFont));
			cell.setBackgroundColor(color);
			this.addCell(cell);
		}
		catch (Exception ex) {
			log.error("Exception caught while adding job row for job = " + job.getId(), ex);
			throw new VectricsException("Exception caught while adding job row for job = " + job.getId(), ex);
		}	
	}   
	
	protected String getCompanyName(Job job) {
		String name = "";
		if (job != null) {
			Company company = job.getCompany();
			if (company == null) {
				name = company.getName();
			}
		}
		return(name);
	}

	
	
	/**
	 * @return Returns the activeOnly.
	 */
	public boolean getActiveOnly() {
		return activeOnly;
	}

	/**
	 * @param activeOnly The activeOnly to set.
	 */
	public void setActiveOnly(boolean activeOnly) {
		this.activeOnly = activeOnly;
	}


	/**
	 * @return Returns the company.
	 */
	public Company getCompany() {
		return company;
	}

	/**
	 * @param company The company to set.
	 */
	public void setCompany(Company company) {
		this.company = company;
	}

}
